package com.example.tbplus14.transaction.impl;

import com.example.tbplus14.transaction.TestTransactionService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.support.TransactionCallback;
import org.springframework.transaction.support.TransactionTemplate;

import javax.annotation.Resource;

@Slf4j
@Service
public class TestTransactionServiceImpl implements TestTransactionService {

    @Resource
    private TransactionTemplate transactionTemplate;

    /**
     * 文章地址
     * https://juejin.cn/post/7511036916898267174
     */
    @Override
    public void testTrans() {
        transactionTemplate.execute((TransactionCallback<Void>) status -> {
            try {
                // 事务操作

                return null;
            } catch (Exception e) {
                log.error("事务执行异常", e);
                // 异常回滚
                status.setRollbackOnly();
                throw new RuntimeException(e);
            }
        });
    }
}
